package com.itheima.health.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.health.dto.SetmealDTO;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.mapper.SetmealMapper;
import com.itheima.health.pojo.CheckGroup;
import com.itheima.health.pojo.CheckItem;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.CheckGroupService;
import com.itheima.health.service.SetmealService;
import com.itheima.health.utils.resources.RedisConstant;
import com.itheima.health.utils.resources.RedisMessageConstant;
import com.itheima.health.vo.CheckGroupVO;
import com.itheima.health.vo.SetmealVO;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(retries = 0,timeout = 10000)
@Transactional
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private  CheckGroupService checkGroupService;

    @Override
    public Map showEditData(Integer id) {
        // 查询检查组
        Setmeal formData = getById(id);
        // 查询检查组id在中间表对应的检查项
        Integer[] checkitemIds = baseMapper.findCheckGroupIdsByCheckMealId(id);
        // 查询所有检查项
        List<CheckGroup> tableData = checkGroupService.findAllCheckGroup();
        Map map = new HashMap();
        map.put("formData",formData);
        map.put("checkgroupIds",checkitemIds);
        map.put("tableData",tableData);
        return map;
    }

    @Override
    public List<Setmeal> findAllSetmeal() {
        List<Setmeal> list=new ArrayList<>();
        list = redisTemplate.opsForList().range("setmealListCache", 0, -1);
        if (list.size()==0){
            list=baseMapper.findAll();
            redisTemplate.opsForList().rightPushAll("setmealListCache",list);
        }
        return list;
    }


    @Override
    public void saveSetemal(SetmealDTO setmealDto) {
        // 如果编辑，删除中间表对应数据
        Integer mealId = setmealDto.getId();
        if (mealId != null) {
            baseMapper.deleteCheckMealAndCheckGroupByMealId(mealId);
        }
        // 保存或更新checkMeal
        saveOrUpdate(setmealDto);
        mealId = setmealDto.getId();

        // 保存中间表
        Integer[] groupIds = setmealDto.getCheckgroupIds();

        // 保存到redis
        // 注意此时可能没有上传图片，所以要判空
        if (setmealDto.getImg() != null) {
            redisTemplate.opsForSet().add(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setmealDto.getImg());
        }
        for (Integer itemId : groupIds) {
            baseMapper.addCheckMeal_CheckGroup(mealId,itemId);
        }
        redisTemplate.delete("setmealListCache");
        redisTemplate.boundHashOps("setmealInfo").delete(Integer.toString(mealId));
    }


    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //  mp   配置插件：  完成分页 查询
        QueryWrapper<Setmeal> queryWrapper = new QueryWrapper();//   封装查询条件
        Page<Setmeal> page =null ;
       if(StringUtils.isEmpty(queryPageBean.getQueryString())){
            page = page(new Page<Setmeal>(queryPageBean.getCurrentPage(), queryPageBean.getPageSize()),queryWrapper);
       }else{
         //   select  * from  xxxx where  name like  or  code like  ? xxx  limit ?,?
           queryWrapper.and(i->i.like("name",queryPageBean.getQueryString()).or().like("HELPCODE",queryPageBean.getQueryString()));
           page = page(new Page<Setmeal>(queryPageBean.getCurrentPage(), queryPageBean.getPageSize()),queryWrapper);
       }
        PageResult result = new PageResult(page.getTotal(),page.getRecords());
        return result;
    }

    @Override
    public SetmealVO findSetMealDetail(int id) {
        //  拆分单sql   1.  查询套餐基本信息
          SetmealVO   setmealVO = baseMapper.findSetMealById(id);
          //  2. 根据套餐id  查询对应得检查组信息
         List<CheckGroupVO> checkGroupVOList =  baseMapper.findCheckGroupsBySetmealId(id);

          //3  根据检查组id  查询对应检查项信息
        for (CheckGroupVO checkGroupVO : checkGroupVOList) {
            List<CheckItem> checkItemList = checkGroupService.findCheckItemByGid(checkGroupVO.getId());
            checkGroupVO.setCheckItemList(checkItemList);
        }
        setmealVO.setCheckGroups(checkGroupVOList);//  查询的检查组信息 封装到套餐对象中
        return setmealVO;
    }
//
//    @Override
//    public Map findCheckItemInfoByGroupId(int id) {
//        Map map  = new HashMap();
//        List<CheckItem> list = checkItemService.list();
//        map.put("checkitems",list);
//        //  根据检查组id  去中间表查询 对应检查项ids
//        int[]  checkItemIds = baseMapper.findCheckItemIdsByGroupId(id);
//        map.put("checkitemIds",checkItemIds);
//        return map;
//    }

}



